import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Card, Col, Input, Row, Select, Icon, Modal, notification } from 'antd';
import React, { useState, useEffect, useCallback,Fragment } from 'react';
import { connect } from 'dva';
import TableForm from './components/TableForm';
import { useRequest } from '@umijs/hooks';
import PassengerListTable from './components/PassengerListTable';
import ObjectOfApproval from './components/ObjectOfApproval';
import PaymentMethod from './components/PaymentMethod';
import InfoModal from './components/InfoModal';
import styles from './style.less';
import Title from '../indemnitySheet/components/Title/Title';
import router from 'umi/router';
import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

import {
  isAocPerson,
  getPassengerList,
  getCompensationDetail,
  getSegment,
  getPassengerListData,
  queryCompensationBaseInfo,
  submitCompensation,
} from './service';
import { transform } from 'lodash';

let isJuge = 0; // 判断是提交还是保存

const { Option } = Select;
const { confirm } = Modal;
const { TextArea } = Input;

// 舱位代表公务舱
const shippingSpace = ['C', 'A', 'D', 'I'];

const IndemnityForm = props => {
  const {
    form: { getFieldDecorator, setFieldsValue, getFieldValue },
    location: { state },
  } = props;
  const [current, handleCurrent] = useState(1);
  const [pageSize, handlePageSize] = useState(1000);
  const [total, handleTotal] = useState(0);
  const [childRatio, setChildRatio] = useState(50) // 儿童比例默认值
  const [babyRatio, setBabyRatio] = useState(10) // 婴儿比例默认值

  const [disBtn, handleBtn] = useState(false);

  const [isFlag, handleIsFlag] = useState(false);

  const [tableLoading, setTableLoading] = useState(true);

  // 航站下拉框数据
  const [hZSelectData, handleHZSelectData] = useState([]);
  // 航站数据
  const [segmentData, setSegmentData] = useState({});


  // 旅客维护选中了数据展示到已选中旅客列表
  const [checkedPassengerList, handelCheckedList] = useState([]);

  // 控制旅客维护弹窗
  const [createModalVisible, handleModalVisible] = useState(false);

  // 控制已选择旅客表格
  const [isTable, handleTable] = useState(false);

  // 存储航班基本信息
  const [flightInfo, handleFlightInfo] = useState({});

  // 存储补偿单ID
  const [orderId, handleOrderId] = useState('');
  //通过补偿单跳转获取补偿信息,存储事故单id
  const [toaccidentId, handleaccidentId] = useState('');
  //补偿事故事故单类型ID
  const [payType, handlepayType] = useState('0');
  //通过补偿单跳转获取补偿信息,存储航班号
  const [toflightDate, handleFlightDate] = useState('');
  //补偿事故事故单航班时间
  const [toflightNo, handleFlightNo] = useState('');
  // 控制审批弹窗
  const [spModal, handleSPModal] = useState(false);
  // 赔偿单类型
  const [compensateType, setCompensateType] = useState('');

  // 存储事故单类型
  const [accidentType, setAccidentType] = useState('');

  useEffect(() => {
    if (JSON.stringify(state) == "{}" || !state) {
      notification.info({
        description: '页面参数不能为空',
        message: '系统提示',
      });
      router.push({
        pathname: '/compensation/indemnitySheet',
      })
      clearTabs();
    }
  }, [state]);

  // 提交新增补偿单数据
  const { loading: subLoading, run } = useRequest(data => submitCompensation(data), {
    manual: true,
    onSuccess: data => {
      if (data) {
        notification.success({
          message: '提示',
          description: isJuge ? '提交成功' : '保存成功',
          duration: 3,
        });
        clearTabs();
        let backUrl = window.localStorage.getItem('indemnityFormBackUrl');
        router.push({
          pathname: backUrl ? backUrl : '/compensation/indemnitySheet',
        });
      }
    },
  });

  // 旅客维护表数据 passengersMaintenance
  const {
    data: passengerDataTable = [],
    loading: passengerLoading,
    run: queryPassengerMaintenance,
  } = useRequest(flightInfo => getPassengerList(flightInfo), {
    manual: true,
    onSuccess: () => {
      handleModalVisible(true);
    },
  });

  // 计算总金额
  const calculatedAmount = (eMoney, gMoney, tMoney, type) => {
    let adult = 0;
    let child = 0;
    let infant = 0;
    let countMoney = 0;
    checkedPassengerList &&
      checkedPassengerList.forEach(v => {
        if (v.withBaby === "Y") {
          infant++;
          adult++;
        } else if (v.isChild === "Y") {
          child++;
        } else {
          adult++;
        }
        if (!tMoney) {
          if (type == '2') {
            if (eMoney % 100 == 0 && eMoney <= 10000) {
              if (v.withBaby === "Y") {
                countMoney += Number(eMoney) + Number(eMoney) * 10 / 100;
              } else if (v.isChild === "Y") {
                countMoney += Number(eMoney) * 50 / 100;
              } else {
                countMoney += Number(eMoney);
              }
            }
          } else {
            if (gMoney % 100 == 0 && gMoney <= 10000) {
              if (v.withBaby === "Y") {
                countMoney += Number(gMoney) + Number(gMoney) * 10 / 100;
              } else if (v.isChild === "Y") {
                countMoney += Number(gMoney) * 50 / 100;
              } else {
                countMoney += Number(gMoney);
              }
            }
          }
        } else {
          countMoney = Number(tMoney) * checkedPassengerList.length;
        }
      });
    if ((state && state?.type) === 'examine') {
    } else {
      let mans = 0; //计算人数
      for (let item of checkedPassengerList) {
        if (item.withBaby === 'Y') {
          mans += 1;
        }
      }
      setFieldsValue({
        personTotalCount: mans + checkedPassengerList.length,
        membersCount: `${adult}/${child}/${infant}`,
        totalMoney: countMoney,
      });
    }
  };

  useEffect(() => {
    calculatedAmount(
      getFieldValue('cpsNum'),
      getFieldValue('cpsNumG'),
      getFieldValue('tktPriceDiff'),
      '1'
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [checkedPassengerList]);

  // 获取基本信息参数
  if (state && state?.type === 'add') {
    if (state?.editInfo) {
      // 航站下拉框数据
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const { run: getSegmentD } = useRequest(params => getSegment(params), {
        manual: true,
        onSuccess: segmentD => {
          setSegmentData(segmentD);
          let hDdatas = [
            { lable: segmentD.aName, value: segmentD.aCode },
            { lable: segmentD.bName, value: segmentD.bCode },
          ];
          if (segmentD.cCode) {
            hDdatas.push({ lable: segmentD.cName, value: segmentD.cCode })
          }
          handleHZSelectData(hDdatas);
        },
      });
      // 通过id获取补偿单详细信息
      let orderId = state?.editInfo.orderId;
      // eslint-disable-next-line react-hooks/rules-of-hooks
      useRequest(() => getCompensationDetail({ orderId }), {
        onSuccess: result => {
          setAccidentType(result.orderDetailInfo.accidentType || ''); // 事故单类型
          handleTable(true);
          let minutes = 0;
          if (result.orderDetailInfo.etd && result.orderDetailInfo.std) {
            let a = moment(`${result.orderDetailInfo.flightDate} ${result.orderDetailInfo.etd}`);
            let b = moment(`${result.orderDetailInfo.flightDate} ${result.orderDetailInfo.std}`);
            minutes = Math.abs(a.diff(b, 'minute')) || 0;
          } else {
            minutes = 0;
          }
          let segment = result.orderDetailInfo.choiceSegment;
          handleFlightInfo({
            flightNo: result.orderDetailInfo.flightNo,
            flightNumber: result.orderDetailInfo.flightNo,
            flightDate: result.orderDetailInfo.flightDate,
            choiceSegment: segment,
            // 添加编辑参数
            orig: result.orderDetailInfo.orig, //始发三字码
            dest: result.orderDetailInfo.dest,//到达三字码
          });
          getSegmentD({
            flightNo: result.orderDetailInfo.flightNo,
            flightDate: result.orderDetailInfo.flightDate,
          });
          setFieldsValue({
            flightId: result.orderDetailInfo.flightId,
            acType: result.orderDetailInfo.acType,
            payType: result.orderDetailInfo.payType,
            orderId: result.orderDetailInfo.orderId,
            accidentId: result.orderDetailInfo.accidentId,
            // 服务航站要请求数据
            serviceCity: result.orderDetailInfo.serviceSegment,
            flightNo: result.orderDetailInfo.flightNo,
            flightDate: result.orderDetailInfo.flightDate,
            choiceSegment: result.orderDetailInfo.choiceSegment,
            planeCode: result.orderDetailInfo.planeCode,
            etd: result.orderDetailInfo.etd,
            std: result.orderDetailInfo.std,
            delayTime: `${Math.round(minutes / 60)} 小时`,
            lateReason: result.orderDetailInfo.lateReason,
            cpsNum: result['eCompensateInfo'].cpsNum,
            childStd: result['eCompensateInfo'].childStd,
            babyStd: result['eCompensateInfo'].babyStd,
            cpsNumG: result['bCompensateInfoVo'].cpsNum,
            childStdG: result['bCompensateInfoVo'].childStd,
            babyStdG: result['bCompensateInfoVo'].babyStd,
            tktPriceDiff: result['customCompensateInfo'].cpsNum,
            totalMoney: result.orderDetailInfo.totalMoney,
            paymentMoney: result.orderDetailInfo.paymentMoney,
            personTotalCount: result.orderDetailInfo.personTotalCount,
            membersCount: result.orderDetailInfo.membersCount,
            remark: result.orderDetailInfo.remark,
            orderRemark: result.orderDetailInfo.orderRemark,
          });
        },
      });
      // 已选旅客列表
      // eslint-disable-next-line react-hooks/rules-of-hooks
      useRequest(() => getPassengerListData({ orderId, current, pageSize }), {
        onSuccess: selectdPassengerList => {
          setTableLoading(false);
          handleTotal(selectdPassengerList.total);
          handleCurrent(selectdPassengerList.current);
          handlePageSize(selectdPassengerList.pageSize);
          handelCheckedList(Array.from(selectdPassengerList.data));
        },
        onError: err => {
          setTableLoading(false);
        },
        // refreshDeps: [current, pageSize],
      });
    } else {
      let flightInfos = {
        flightNo: state?.flightInfo.flighN,
        flightDate: state?.flightInfo.flightD.replace(/\//g, '-'),
        choiceSegment: state?.flightInfo.hData,
      };
      // 航站下拉框数据获取
      // eslint-disable-next-line react-hooks/rules-of-hooks
      useRequest(
        () =>
          getSegment({
            flightNo: state?.flightInfo.flighN,
            flightDate: state?.flightInfo.flightD,
          }),
        {
          onSuccess: segmentD => {
            setSegmentData(segmentD);
            let hDdatas = [
              { lable: segmentD.aName, value: segmentD.aCode },
              { lable: segmentD.bName, value: segmentD.bCode },
            ];
            if (segmentD.cCode) {
              hDdatas.push({ lable: segmentD.cName, value: segmentD.cCode })
            }
            handleHZSelectData(hDdatas);
          },
        },
      );

      // 基本信息数据
      // eslint-disable-next-line react-hooks/rules-of-hooks
      useRequest(() => queryCompensationBaseInfo(flightInfos), {
        onSuccess: data => {
          let segment = state?.flightInfo.hData;
          handleFlightInfo({
            flightNo: state?.flightInfo.flighN,
            flightNumber: state?.flightInfo.flighN,
            flightDate: state?.flightInfo.flightD.replace(/\//g, '-'),
            choiceSegment: segment,
          });
          let delayTimes = '';
          if (data[0].etd && data[0].std) {
            if (data[0].etd.split(',').length === 1 && data[0].std.split(',').length === 1) {
              let a = moment(`${data[0].flightDate} ${data[0].etd}`);
              let b = moment(`${data[0].flightDate} ${data[0].std}`);
              let minutes = Math.abs(a.diff(b, 'minute')) || 0;
              delayTimes = `${Math.round(minutes / 60)} 小时`;
            }
          }
          // 初始化设置基本信息
          setFieldsValue({
            flightId: data[0].flightId,
            acType: data[0].acType,
            flightNo: data[0].flightNo,
            flightDate: data[0].flightDate,
            choiceSegment: state?.flightInfo.hData,
            planeCode: data[0].acReg ? data[0].acReg : '',
            etd: data[0].etd ? data[0].etd : '',
            std: data[0].std ? `${data[0].std}` : '',
            delayTime: delayTimes,
            lateReason: data[0].delay_reason ? data[0].delay_reason : '',
          });
        },
      });
    }
  }
  if (state && state?.type === 'examine') {
    // 航站下拉框数据
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const { run: getSegmentD } = useRequest(params => getSegment(params), {
      manual: true,
      onSuccess: segmentD => {
        setSegmentData(segmentD);
        let hDdatas = [
          { lable: segmentD.aName, value: segmentD.aCode },
          { lable: segmentD.bName, value: segmentD.bCode },
        ];
        if (segmentD.cCode) {
          hDdatas.push({ lable: segmentD.cName, value: segmentD.cCode })
        }
        handleHZSelectData(hDdatas);
      },
    });
    // 通过id获取补偿单详细信息
    let orderId = state?.orderId;
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useRequest(() => getCompensationDetail({ orderId }), {
      onSuccess: result => {
        setAccidentType(result?.orderDetailInfo?.accidentType || ''); // 事故单类型
        const _compensateType = result?.orderDetailInfo?.compensateType
        setCompensateType(_compensateType); // 赔偿单类型 0临时 1结案
        let minutes = 0;
        if (result.orderDetailInfo.etd && result.orderDetailInfo.std) {
          let a = moment(`${result.orderDetailInfo.flightDate} ${result.orderDetailInfo.etd}`);
          let b = moment(`${result.orderDetailInfo.flightDate} ${result.orderDetailInfo.std}`);
          minutes = Math.abs(a.diff(b, 'minute')) || 0;
        } else {
          minutes = 0;
        }
        handleaccidentId(result.orderDetailInfo.accidentId);
        handlepayType(result.orderDetailInfo.payType);
        handleFlightDate(result.orderDetailInfo.flightDate);
        handleFlightNo(result.orderDetailInfo.flightNo);
        handleTable(true);
        handleOrderId(orderId);
        handleFlightInfo({
          flightNo: result.orderDetailInfo.flightNo,
          flightDate: result.orderDetailInfo.flightDate,
          flightNumber: result.orderDetailInfo.flightNo,
        });
        getSegmentD({
          flightNo: result.orderDetailInfo.flightNo,
          flightDate: result.orderDetailInfo.flightDate,
        });
        setFieldsValue({
          flightId: result.orderDetailInfo.flightId,
          acType: result.orderDetailInfo.acType,
          payType: result.orderDetailInfo.payType,
          orderId: result.orderDetailInfo.orderId,
          accidentId: result.orderDetailInfo.accidentId,
          // 服务航站要请求数据
          serviceCity: result.orderDetailInfo.serviceSegment,
          flightNo: result.orderDetailInfo.flightNo,
          flightDate: result.orderDetailInfo.flightDate,
          choiceSegment: result.orderDetailInfo.choiceSegment,
          planeCode: result.orderDetailInfo.planeCode,
          etd: result.orderDetailInfo.etd,
          std: result.orderDetailInfo.std,
          delayTime: `${Math.round(minutes / 60)} 小时`,
          lateReason: result.orderDetailInfo.lateReason,
          cpsNum:
            result.orderDetailInfo.payType === '1'
              ? result.orderDetailInfo.totalMoney
              : result['eCompensateInfo'].cpsNum,
          childStd: result['eCompensateInfo'].childStd,
          babyStd: result['eCompensateInfo'].babyStd,
          cpsNumG:
            result.orderDetailInfo.payType === '1'
              ? result.orderDetailInfo.totalMoney
              : result['bCompensateInfoVo'].cpsNum,
          childStdG: result['bCompensateInfoVo'].childStd,
          babyStdG: result['bCompensateInfoVo'].babyStd,
          payMoneyG: result['customCompensateInfo'].cpsNum,
          tktPriceDiff: result['customCompensateInfo'].cpsNum,
          totalMoney: result.orderDetailInfo.totalMoney,
          paymentMoney: result.orderDetailInfo.paymentMoney,
          personTotalCount: result.orderDetailInfo.personTotalCount,
          membersCount: result.orderDetailInfo.membersCount,
          remark: result.orderDetailInfo.remark,
          orderRemark: result.orderDetailInfo.orderRemark,
          paymentReason: result.orderDetailInfo.paymentReason,
          transportPay: result.orderDetailInfo.transportPay,
          overWeightPay: result.orderDetailInfo.overWeightPay,
        });
      },
    });

    // 已选旅客列表 和 旅客维护数据
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useRequest(() => getPassengerListData({ orderId, current, pageSize }), {
      onSuccess: selectdPassengerList => {
        setTableLoading(false);
        handleTotal(selectdPassengerList.total);
        handleCurrent(selectdPassengerList.current);
        handlePageSize(selectdPassengerList.pageSize);
        handelCheckedList(selectdPassengerList.data);
      },
      onError: err => {
        setTableLoading(false);
      },
      // refreshDeps: [current, pageSize],
    });
  }

  useEffect(() => {
    if (state && state?.status) {
      if (state?.status === '3') {
        handleIsFlag(false);
      } else {
        handleIsFlag(true);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  //经济舱规则
  const moneyValidator = (rule, value, callback) => {
    handleBtn(false);
    if (value === '' || (value % 100 != 0 || value > 10000)) {
      callback('请输入倍数为100的整数(不大于10000)');
    } else if (value && !/^[1-9]\d*$/.test(value)) {
      handleBtn(true);
      callback('请输入正确的金额');
    } else {
      props.form.setFieldsValue({
        cpsNumG: value,
        cpsNum: value,
      });
      // 上面三个标准不为0，差价就为0
      if (value != 0) {
        props.form.setFieldsValue({
          tktPriceDiff: 0,
        });
      }
      callback();
    }
  };
  //自定义金额规则
  const moneyValidators = (rule, value, callback) => {
    handleBtn(false);
    if (value && value > 9999) {
      handleBtn(true);
      callback('当前金额已超出最大权限金额，请核对!');
    } else if (value && !/^[1-9]\d*$/.test(value)) {
      handleBtn(true);
      callback('请输入正确的金额');
    } else {
      props.form.setFieldsValue({
        cpsNumG: value == 0 ? 200 : 0,
        cpsNum: value == 0 ? 200 : 0,
      });
      setChildRatio(value == 0 ? 50 : 0);
      setBabyRatio(value == 0 ? 10 : 0);
      callback();
    }
  };

  const [isCancel, handleCancel] = useState(false);

  // 控制已选择旅客表格
  const toggleTable = () => {
    isTable ? handleTable(false) : handleTable(true);
  };

  // 保存为草稿
  const saveDraft = () => {
    let currentAmount = 0;
    for (let item of checkedPassengerList) {
      if (getFieldValue('tktPriceDiff') == '0') {
        currentAmount = item.isChild === 'N' ?
          (item.withBaby === 'N' ? getFieldValue('cpsNum') : (Number((getFieldValue('cpsNum') * 10) / 100) + Number(getFieldValue('cpsNum')))) :
          (getFieldValue('cpsNum') * 50) / 100;
      } else {
        currentAmount = getFieldValue('tktPriceDiff')
      }
      item.paxId = item.idx;
      item.paxName = item.psgName;
      item.idNo = item.idNum;
      item.sex = item.gender;
      item.telephone = item.phone;
      item.orgCityAirp = item.orig;
      item.dstCityAirp = item.dest;
      item.tktNo = item.etNum;
      item.tktDate = item.printTicketTime;
      item.currentAmount = currentAmount;
    }
    isJuge = 0;
    let obj = {
      orderInfo: {
        orderId: getFieldValue('orderId'),
        flightId: getFieldValue('flightId'),
        flightNo: getFieldValue('flightNo'),
        flightDate: getFieldValue('flightDate').replace(/\//g, '-'),
        serviceCity: getFieldValue('serviceCity'),
        payType: getFieldValue('payType'),
        choiceSegment: getFieldValue('choiceSegment'),
        etd: getFieldValue('etd'),
        std: getFieldValue('std'),
        dst: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.dst, //到达航站
        org: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.org, //起飞航站
        planeCode: getFieldValue('planeCode'),
        acType: getFieldValue('acType'),
        delayTime: getFieldValue('delayTime'),
        lateReason: getFieldValue('lateReason'),
        remark: getFieldValue('remark'),
        totalMoney: getFieldValue('totalMoney'),
        status: '0',
        paymentClass: "1",
      },
      paxInfoList: checkedPassengerList,
      // 补偿标准
      compensateInfoList: getFieldValue('tktPriceDiff') == '0' ? [
        { "cpsNum": getFieldValue('cpsNum'), "babyStd": 50, "childStd": 10, "classType": "1", "activityCode": null }, //经济舱
        { "cpsNum": getFieldValue('cpsNumG'), "babyStd": 50, "childStd": 10, "classType": "2", "activityCode": null }, //公务/头等舱
      ] : [
        { "cpsNum": getFieldValue('tktPriceDiff'), "babyStd": 0, "childStd": 0, "classType": "3", "activityCode": null }, //自定义金额
      ],
    };
    if (!getFieldValue('tktPriceDiff')) {
      if (Number(getFieldValue('cpsNum')) == '' || (Number(getFieldValue('cpsNum')) % 100 != 0 || Number(getFieldValue('cpsNum')) > 10000)) {
        return
      }
      if (Number(getFieldValue('cpsNumG')) == '' || (Number(getFieldValue('cpsNumG')) % 100 != 0 || Number(getFieldValue('cpsNumG')) > 10000)) {
        return
      }
    }
    run(obj);
  };

  // 提交基本信息数据
  const submitBaseInfoData = () => {
    let currentAmount = 0;
    for (let item of checkedPassengerList) {
      if (getFieldValue('tktPriceDiff') == '0') {
        currentAmount = item.isChild === 'N' ?
          (item.withBaby === 'N' ? getFieldValue('cpsNum') :
            (Number((getFieldValue('cpsNum') * 10) / 100) + Number(getFieldValue('cpsNum')))) :
          (getFieldValue('cpsNum') * 50) / 100;
      } else {
        currentAmount = getFieldValue('tktPriceDiff')
      }
      item.paxId = item.idx;
      item.paxName = item.psgName;
      item.idNo = item.idNum;
      item.sex = item.gender;
      item.telephone = item.phone;
      item.orgCityAirp = item.orig;
      item.dstCityAirp = item.dest;
      item.tktNo = item.etNum;
      item.tktDate = item.printTicketTime;
      item.currentAmount = currentAmount;
    }
    isJuge = 1;
    let obj = {
      orderInfo: {
        orderId: getFieldValue('orderId'),
        flightId: getFieldValue('flightId'),
        flightNo: getFieldValue('flightNo'),
        flightDate: getFieldValue('flightDate').replace(/\//g, '-'),
        serviceCity: getFieldValue('serviceCity'),
        payType: getFieldValue('payType'),
        choiceSegment: getFieldValue('choiceSegment'),
        etd: getFieldValue('etd'),
        std: getFieldValue('std'),
        dst: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.dst, //到达航站
        org: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.org, //起飞航站
        planeCode: getFieldValue('planeCode'),
        acType: getFieldValue('acType'),
        delayTime: getFieldValue('delayTime'),
        lateReason: getFieldValue('lateReason'),
        remark: getFieldValue('remark'),
        totalMoney: getFieldValue('totalMoney'),
        status: '1',
        paymentClass: "1",
      },
      paxInfoList: checkedPassengerList,
      // 补偿标准
      compensateInfoList: getFieldValue('tktPriceDiff') == '0' ? [
        { "cpsNum": getFieldValue('cpsNum'), "babyStd": 50, "childStd": 10, "classType": "1", "activityCode": null }, //经济舱
        { "cpsNum": getFieldValue('cpsNumG'), "babyStd": 50, "childStd": 10, "classType": "2", "activityCode": null }, //公务/头等舱
      ] : [
        { "cpsNum": getFieldValue('tktPriceDiff'), "babyStd": 0, "childStd": 0, "classType": "3", "activityCode": null }, //自定义金额
      ],
    };
    if (!getFieldValue('tktPriceDiff')) {
      if (Number(getFieldValue('cpsNum')) == '' || (Number(getFieldValue('cpsNum')) % 100 != 0 || Number(getFieldValue('cpsNum')) > 10000)) {
        return
      }
      if (Number(getFieldValue('cpsNumG')) == '' || (Number(getFieldValue('cpsNumG')) % 100 != 0 || Number(getFieldValue('cpsNumG')) > 10000)) {
        return
      }
    }
    if (
      (Number(getFieldValue('cpsNum')) ||
        Number(getFieldValue('cpsNumG')) ||
        Number(getFieldValue('tktPriceDiff'))) &&
      checkedPassengerList.length
    ) {
      run(obj);
    } else {
      notification.error({
        message: '提示',
        description: '补偿标准或者自定义金额至少一项不为空, 已选旅客不能为空',
        duration: 3,
      });
    }
  };
  // 关闭新开的tab
  const clearTabs = () => {
    props.dispatch({
      type: 'auditDetail/removeTabs',
      payload: {
        removeTabsPathname: props.location.pathname
      }
    });
  }
  // 关闭审批弹窗
  const closeSPModal = useCallback(() => {
    handleSPModal(false);
  }, []);

  // 确定审批弹窗
  const sureSPModal = useCallback(
    info => {
      let currentAmount = 0;
      for (let item of checkedPassengerList) {
        if (getFieldValue('tktPriceDiff') == '0') {
          currentAmount = item.isChild === 'N' ?
            (item.withBaby === 'N' ? getFieldValue('cpsNum') : (Number((getFieldValue('cpsNum') * 10) / 100) + Number(getFieldValue('cpsNum')))) :
            (getFieldValue('cpsNum') * 50) / 100;
        } else {
          currentAmount = getFieldValue('tktPriceDiff')
        }
        item.paxId = item.idx;
        item.paxName = item.psgName;
        item.idNo = item.idNum;
        item.sex = item.gender;
        item.telephone = item.phone;
        item.orgCityAirp = item.orig;
        item.dstCityAirp = item.dest;
        item.tktNo = item.etNum;
        item.tktDate = item.printTicketTime;
        item.currentAmount = currentAmount;
      }
      let obj = {
        orderInfo: {
          orderId: getFieldValue('orderId'),
          flightId: getFieldValue('flightId'),
          flightNo: getFieldValue('flightNo'),
          flightDate: getFieldValue('flightDate').replace(/\//g, '-'),
          serviceCity: getFieldValue('serviceCity'),
          payType: getFieldValue('payType'),
          choiceSegment: getFieldValue('choiceSegment'),
          etd: getFieldValue('etd'),
          std: getFieldValue('std'),
          dst: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.dst, //到达航站
          org: state?.editInfo && state?.editInfo.selectRows && state?.editInfo.selectRows.org, //起飞航站
          planeCode: getFieldValue('planeCode'),
          acType: getFieldValue('acType'),
          delayTime: getFieldValue('delayTime'),
          lateReason: getFieldValue('lateReason'),
          remark: getFieldValue('remark'),
          totalMoney: getFieldValue('totalMoney'),
          status: '1',
          auditor: info,
          paymentClass: "1",
        },
        paxInfoList: checkedPassengerList,
        // 补偿标准
        compensateInfoList: getFieldValue('tktPriceDiff') == '0' ? [
          { "cpsNum": getFieldValue('cpsNum'), "babyStd": 50, "childStd": 10, "classType": "1", "activityCode": null }, //经济舱
          { "cpsNum": getFieldValue('cpsNumG'), "babyStd": 50, "childStd": 10, "classType": "2", "activityCode": null }, //公务/头等舱
        ] : [
          { "cpsNum": getFieldValue('tktPriceDiff'), "babyStd": 0, "childStd": 0, "classType": "3", "activityCode": null }, //自定义金额
        ],
      };
      if (!getFieldValue('tktPriceDiff')) {
        if (Number(getFieldValue('cpsNum')) == '' || (Number(getFieldValue('cpsNum')) % 100 != 0 || Number(getFieldValue('cpsNum')) > 10000)) {
          return
        }
        if (Number(getFieldValue('cpsNumG')) == '' || (Number(getFieldValue('cpsNumG')) % 100 != 0 || Number(getFieldValue('cpsNumG')) > 10000)) {
          return
        }
      }
      run(obj);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    },
    [checkedPassengerList],
  );
  // console.log(toaccidentId)
  return (
    <>
      <Title title="基本信息" />
      <Card className={styles.card}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col sm={12} md={6}>
              <Form.Item label="补偿类型：">
                {getFieldDecorator('payType', {
                  initialValue: '0',
                })(
                  <Select disabled>
                    <Option value="0">不正常航班</Option>
                    <Option value="1">异常行李</Option>
                    <Option value="2">旅客超售</Option>
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col sm={12} md={6}>
              <Form.Item label="补偿单号：">
                {getFieldDecorator('orderId', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col sm={12} md={6}>
              <Form.Item
                label={
                  <span>
                    事故单号：
                    {payType && payType !== '0' ? (
                      <span
                        style={{
                          cursor: 'pointer',
                          textDecoration: 'underline',
                          color: '#E13B3B',
                          marginRight: '15px',
                        }}
                        onClick={() => {
                          let resourceStr = window.localStorage.getItem('resource');
                          // 不正常航班补偿0、异常行李1、旅客超售2
                          if (payType === '1') {
                            const urlObj = {
                              '1': '/banksearchSystem/inPortBaggageManagement/damagedBaggageManagement',
                              '2': '/banksearchSystem/inPortBaggageManagement/lessBaggageManagement',
                              '6': '/banksearchSystem/inPortBaggageManagement/internalMissingManagement',
                              '7': '/banksearchSystem/outPortBaggageManagement/damagedBaggageManagement'
                            }
                            // 对行查的页面鉴权
                            let toPathUrl = urlObj[accidentType + ''];
                            if (resourceStr.indexOf(toPathUrl) == -1) {
                              return  notification.info({
                                message: '您当前无权限进行查看',
                              });
                            }
                            if (toPathUrl) {
                              window.sessionStorage.setItem('isFromCompensate','1');
                              router.push({
                                pathname: toPathUrl,
                                state: {
                                  accidentId: toaccidentId
                                }
                              })
                            }
                            // sessionStorage.setItem('firstLoad', '1');
                            // router.push({
                            //   pathname: '/compensation/luggageindex',
                            //   state: {
                            //     accidentId: toaccidentId,
                            //     flightDate: toflightDate,
                            //     flightNo: toflightNo,
                            //   },
                            // });
                          }
                          if (payType === '2') {
                            if (resourceStr.indexOf('"path":"/compensation/oversaleindex') == -1) {
                              return  notification.info({
                                message: '您当前无权限进行查看',
                              });
                            }
                            sessionStorage.setItem('firstLoad', '1');
                            router.push({
                              pathname: '/compensation/oversaleindex',
                              state: {
                                accidentId: toaccidentId,
                                flightDate: toflightDate,
                                flightNo: toflightNo,
                              },
                            });
                          }
                        }}
                      >
                        查看事故单
                      </span>
                    ) : null}
                  </span>
                }
              >
                {getFieldDecorator('accidentId', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col sm={12} md={6}>
              <Form.Item label="服务航站：">
                {getFieldDecorator('serviceCity', {
                  initialValue: hZSelectData[0] && hZSelectData[0].label,
                })(
                  <Select disabled={(state && state?.type) === 'examine' ? true : false}>
                    {hZSelectData && hZSelectData.map(v => {
                      return (
                        <Option key={v.value} value={v.lable}> {v.lable} </Option>
                      );
                    })}
                  </Select>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col md={6} sm={12}>
              <Form.Item label="航班号：">
                {getFieldDecorator('flightNo', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col md={6} sm={12}>
              <Form.Item label="航班日期：">
                {getFieldDecorator('flightDate', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col md={12} sm={24}>
              <Form.Item label="航段：">
                {getFieldDecorator('choiceSegment', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col md={6} sm={12}>
              <Form.Item label="飞机号：">
                {getFieldDecorator('planeCode', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col md={6} sm={12}>
              <Form.Item label="预计起飞：">
                {getFieldDecorator('etd', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col md={6} sm={12}>
              <Form.Item label="计划起飞：">
                {getFieldDecorator('std', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
            <Col md={6} sm={12}>
              <Form.Item label="延误时长：">
                {getFieldDecorator('delayTime', {
                  initialValue: '',
                })(<Input disabled />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col sm={24}>
              {
                payType === '0'
                  ? <Form.Item label="延误原因：">
                    {getFieldDecorator('lateReason', {
                      initialValue: '',
                    })(<Input disabled />)}
                  </Form.Item>
                  : <Form.Item label="备注：">
                    {getFieldDecorator('remark', {
                      initialValue: '',
                    })(<Input disabled />)}
                  </Form.Item>
              }

            </Col>
          </Row>
          <Row>
            <Col>
              <Form.Item label="">
                {getFieldDecorator('flightId', {
                  initialValue: '',
                })(<Input type="hidden" disabled />)}
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label="">
                {getFieldDecorator('acType', {
                  initialValue: '',
                })(<Input type="hidden" disabled />)}
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
      {/* 异常行李相关的两种补偿信息*/}
      <Fragment>
        {+payType !== 1 ? null : <>
          <Fragment>
            {/* 临时补偿单详情 */}
            {+compensateType === 0 && <Fragment>
              <Title title="临时补偿单详情" />
              <Card className={styles.card}>
                <Form layout="vertical">
                  <Row gutter={16}>
                    <Col md={6} sm={12}>
                      <Form.Item label="补偿金额：">
                        {getFieldDecorator('paymentMoney', {
                          initialValue: 0,
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={18} sm={12}>
                      <Form.Item label="补偿原因：">
                        {getFieldDecorator('paymentReason', {
                          initialValue: '',
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={24} sm={24}>
                      <Form.Item label="备注：">
                        {getFieldDecorator('orderRemark', {
                          initialValue: '',
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </Card>
            </Fragment>}
            {/* 结案补偿单详情 */}
            {+compensateType === 1 && <Fragment>
              <Title title="结案补偿单详情" />
              <Card className={styles.card}>
                <Form layout="vertical">
                  <Row gutter={16}>
                    <Col md={8} sm={12}>
                      <Form.Item label="补偿金额：">
                        {getFieldDecorator('paymentMoney', {
                          initialValue: 0,
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={8} sm={12}>
                      <Form.Item label="运输费用：">
                        {getFieldDecorator('transportPay', {
                          initialValue: 0,
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={8} sm={12}>
                      <Form.Item label="超重费用：">
                        {getFieldDecorator('overWeightPay', {
                          initialValue: 0,
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={24} sm={24}>
                      <Form.Item label="补偿原因：">
                        {getFieldDecorator('paymentReason', {
                          initialValue: '',
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                    <Col md={24} sm={24}>
                      <Form.Item label="备注：">
                        {getFieldDecorator('orderRemark', {
                          initialValue: '',
                        })(<Input disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </Card>
            </Fragment>}
          </Fragment>
        </>}
      </Fragment>
      {/* 补偿标准 */}
      <Fragment>
        {+payType === 1 ? null : <>
          <Title title="补偿标准" />
          <Card className={styles.card}>
            {
              payType === '0'
                ? <Form layout="vertical" hideRequiredMark>
                  <Row gutter={16}>
                    <Col md={6}>
                      <Form.Item label="经济舱：">
                        {getFieldDecorator('cpsNum', {
                          initialValue: 200,
                          rules: [
                            {
                              validator: moneyValidator,
                            },
                          ],
                          getValueFromEvent: event => {
                            return event.target.value.replace(/\D/g, '');
                          },
                        })(
                          <Input
                            onChange={e => {
                              calculatedAmount(
                                e.target.value,
                                getFieldValue('cpsNumG'),
                                getFieldValue('tktPriceDiff'),
                                '2'
                              );
                              if (Number(e.target.value) || Number(getFieldValue('cpsNumG'))) {
                                setFieldsValue({
                                  tktPriceDiff: 0,
                                });
                              }
                            }}
                            disabled={(state && state?.type) === 'examine' ? true : false}
                            maxLength={5}
                            placeholder="请输入"
                            addonAfter="(元)"
                          />,
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={6}>
                      <Form.Item label="儿童比例：">
                        <Input value={childRatio} childRatio="(%)" disabled />
                      </Form.Item>
                    </Col>
                    <Col md={6}>
                      <Form.Item label="婴儿比例：">
                        <Input value={babyRatio} addonAfter="(%)" disabled />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col md={6}>
                      <Form.Item label="公务舱：">
                        {getFieldDecorator('cpsNumG', {
                          initialValue: 200,
                          rules: [
                            {
                              validator: moneyValidator,
                            },
                          ],
                          getValueFromEvent: event => {
                            return event.target.value.replace(/\D/g, '');
                          },
                        })(
                          <Input
                            onChange={e => {
                              calculatedAmount(
                                getFieldValue('cpsNum'),
                                e.target.value,
                                getFieldValue('tktPriceDiff'),
                                '3'
                              );
                              if (Number(e.target.value) || Number(getFieldValue('cpsNum'))) {
                                setFieldsValue({
                                  tktPriceDiff: 0,
                                });
                              }
                            }}
                            disabled={state && state?.type === 'examine' ? true : false}
                            maxLength={5}
                            placeholder="请输入"
                            addonAfter="(元)"
                          />,
                        )}
                      </Form.Item>
                    </Col>
                    <Col md={6}>
                      <Form.Item label="儿童比例：">
                        <Input value={childRatio} childRatio="(%)" disabled />
                      </Form.Item>
                    </Col>
                    <Col md={6}>
                      <Form.Item label="婴儿比例：">
                        <Input value={babyRatio} addonAfter="(%)" disabled />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col md={6}>
                      <Form.Item label="自定义金额：">
                        {getFieldDecorator('tktPriceDiff', {
                          initialValue: 0,
                          rules: [
                            {
                              validator: moneyValidators,
                            },
                          ],
                          getValueFromEvent: event => {
                            return event.target.value.replace(/\D/g, '');
                          },
                        })(
                          <Input
                            onChange={e => {
                              calculatedAmount(
                                getFieldValue('cpsNum'),
                                getFieldValue('cpsNumG'),
                                e.target.value,
                                '1'
                              );
                              if (Number(e.target.value)) {
                                setFieldsValue({
                                  cpsNum: 0,
                                  cpsNumG: 0,
                                });
                              }
                            }}
                            disabled={state && state?.type === 'examine' ? true : false}
                            maxLength={4}
                            addonAfter="(元)"
                          />,
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
                : <Form>
                  <Row gutter={16}>
                    <Col md={6} >
                      <Form.Item label='补偿金额：'>
                        {getFieldDecorator('payMoneyG', {
                        })(<Input addonAfter="(元)" disabled />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <div style={{ marginTop: '10px' }}>注：具体补偿信息，详见对应事故单</div>
                </Form>
            }

          </Card>
        </>}
      </Fragment>
      {/* 收款方式 */}
      <Title title="收款方式" />
      <Card>
        <PaymentMethod amoun={200}></PaymentMethod>
      </Card>
      {/* 旅客维护 */}
      <div className={styles.lkpc}>
        <Title title="旅客维护" />
        {/* <AuthComponent authCode="compensation.maintain.showButton"> */}
        <Button
          disabled={isFlag}
          loading={passengerLoading}
          style={{ marginTop: "6px" }}
          onClick={() => {
            if (state && state?.type === 'add') {
              queryPassengerMaintenance({
                flightNumber: flightInfo.flightNo, //航班号
                orig: segmentData.cCode ? ((flightInfo.orig === segmentData.aCode) ? flightInfo.orig : "") : flightInfo.orig, //始发三字码
                dest: segmentData.cCode ? ((flightInfo.orig === segmentData.bCode) ? flightInfo.dest : "") : flightInfo.dest,//到达三字码
                flightStartDate: flightInfo.flightDate, //航班开始时间
                flightEndDate: flightInfo.flightDate, //航班结束时间,
                isCancel: "", //是否取消 默认是
                isPrintTktNo: "Y",//是否出票 默认是
              });
            } else {
              handleModalVisible(true);
            }
          }}
          type="primary"
          icon="edit"
        >
          旅客维护
          </Button>
        {/* </AuthComponent> */}
      </div>
      <Card className={styles.card}>
        <Form layout="vertical" hideRequiredMark>
          <Row gutter={16}>
            <Col md={6}>
              <Form.Item label="合计金额：">
                {getFieldDecorator('totalMoney', {
                  initialValue: 0,
                })(<Input disabled addonAfter="(元)" />)}
              </Form.Item>
            </Col>
            <Col md={6}>
              <Form.Item label="已选旅客：">
                {getFieldDecorator('personTotalCount', {
                  initialValue: '0',
                })(<Input disabled addonAfter="(人)" />)}
              </Form.Item>
            </Col>
            <Col md={6}>
              <Form.Item label="成/童/婴：">
                {getFieldDecorator('membersCount', {
                  initialValue: '0/0/0',
                })(<Input disabled addonAfter="(人)" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col md={24}>
              {
                payType === '0'
                  ? <Form.Item label="备注：">
                    {getFieldDecorator('remark', {
                      initialValue: '',
                    })(
                      <TextArea
                        disabled={(state && state?.type) === 'examine' ? true : false}
                        rows={5}
                        maxLength={500}
                      />,
                    )}
                  </Form.Item>
                  : null
              }

            </Col>
          </Row>
        </Form>
      </Card>
      {/* 已选旅客列表 */}

      <div onClick={toggleTable} className={styles.passengerTitle}>
        <Title title="已选旅客列表" />
        <Icon type={isTable ? 'caret-down' : 'caret-right'} />
      </div>
      <Card
        className={
          isTable && ((state && state?.type === 'examine') || (state && state?.type === 'add'))
            ? styles.showTable
            : styles.hideTable
        }
      >
        <TableForm
          handlePageSize={handlePageSize}
          orderId={state && state?.orderId}
          handleCurrent={handleCurrent}
          editInfo={state && state?.editInfo}
          type={state && state?.type}
          tableLoading={tableLoading}
          setTableLoading={setTableLoading}
          current={current}
          pageSize={pageSize}
          total={total}
          data={checkedPassengerList}
        />
      </Card>
      <div style={{
        padding: '15px 0 30px',
        position: 'fixed',
        bottom: '0',
        display: 'flex',
        left: '50%',
        zIndex: '9',
      }}>
        <Button
          disabled={disBtn}
          loading={subLoading}
          style={{ display: state && state?.type === 'examine' ? 'none' : 'inline-block' }}
          onClick={() => {
            submitBaseInfoData();
          }}
          type="primary"
        >
          提交
        </Button>
        <Button
          disabled={disBtn}
          loading={subLoading}
          onClick={saveDraft}
          style={{
            margin: '0 20px',
            display: state && state?.type === 'examine' ? 'none' : 'inline-block',
          }}
          type="primary"
        >
          保存
        </Button>
        <Button
          onClick={() => {
            clearTabs();
            if (state && state?.type === 'examine') {
              sessionStorage.setItem('historyD', 1);
              let backUrl = window.localStorage.getItem('indemnityFormBackUrl');
              router.push({
                pathname: backUrl ? backUrl : '/compensation/indemnitySheet',
              });
            } else {
              handleCancel(true);
            }
          }}
        >
          关闭
        </Button>
      </div>

      {/* 旅客维护弹窗 */}
      <PassengerListTable
        type={state && state?.type}
        {...{
          handelCheckedList,
          createModalVisible,
          handleModalVisible,
          passengerDataTable,
          handleTable,
          checkedPassengerList,
          orderId,
          flightInfo,
          queryPassengerMaintenance,
          handlePageSize,
          handleCurrent,
          handleTotal,
          segmentData,
          payType
        }}
      />

      {/* 审批对象弹窗 */}
      <ObjectOfApproval sureSPModal={sureSPModal} closeSPModal={closeSPModal} spModal={spModal} />

      <InfoModal handleCancel={handleCancel} modalVisible={isCancel} />
    </>
  );
};
// export default Form.create()(IndemnityForm);
export default connect(state => state?.auditDetail)(Form.create()(IndemnityForm));
